import store from "@/store";
import defaultAvatar from "@/assets/images/profile.png";
import { getToken, setToken, removeToken } from "@/utils/token";
import * as loginApi from "@/api/loginApi";
import * as userApi from "@/api/system/userApi";

const user = {
  state: {
    token: getToken(),
    loginId: JSON.parse(sessionStorage.getItem("loginId")),
    name: "",
    avatar: "",
    role: "",
    permissions: [],
    dictTypes: {},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_LOGIN_ID: (state, loginId) => {
      state.loginId = loginId;
      sessionStorage.setItem("loginId", JSON.stringify(state.loginId));
    },
    SET_USERNAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLE: (state, role) => {
      state.role = role;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // 登录
    login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const { password } = userInfo;
      const { verifyCode } = userInfo;
      const { verifyCodeUUID } = userInfo;
      return new Promise((resolve, reject) => {
        loginApi
          .login(username, password, verifyCode, verifyCodeUUID)
          .then((res) => {
            setToken(res.data.tokenValue);
            commit("SET_LOGIN_ID", res.data.loginId);
            commit("SET_TOKEN", res.data.tokenValue);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    getUserDetail({ commit }) {
      return new Promise((resolve, reject) => {
        const loginId = store.getters.loginId;
        console.log("当前用户ID - loginId : " + loginId);
        userApi
          .getUserDetail(loginId)
          .then((res) => {
            console.log("=============获取用户信息=============");
            console.log(res);
            const avatar =
              res.data.userDTO.avatar === "" || res.data.userDTO.avatar == null
                ? defaultAvatar
                : res.data.userDTO.avatar;
            if (res.data.roles) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLE", res.data.roles);
              commit("SET_PERMISSIONS", res.data.permissions);
            } else {
              commit("SET_ROLE", "ROLE_DEFAULT");
            }
            commit("SET_USERNAME", res.data.userDTO.username);
            commit("SET_AVATAR", avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        loginApi
          .logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLE", null);
            commit("SET_PERMISSIONS", []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
